import 'dart:ui';

import 'package:sqflite/sqflite.dart';

final String tableName = 'table_test';
final String columnId = 'id';     // QQ号
final String columnPwd = 'pwd';    // 密码
final String columnName = 'name';  // 昵称
final String columnDone = 'done';  // 是否记住密码
final String columnPic = 'pic';

class Test{
  String ? id;
  String? pwd;
  String? name;
  bool? done;
  String? pic;
  //toMap() 方法以Map<Stirng, dynamic>的类型返回一个Test实例
  Map<String, dynamic> toMap(){
    var map = <String, dynamic>{
      columnId: id,
      columnPwd: pwd,
      columnName : name,
      columnDone: done == true? 1 : 0,
      columnPic: pic
    };
    // print(map);
    // print(id);
    // if(id != null) {
    //   map[columnId] = id;
    // }
    print(map);
    return map;
  }
//  生成构造函数
  Test();
//  命名构造函数,通过一个Map<String, dynamic>的参数初始化一个Test实例
  Test.fromMap(Map<String, dynamic>map){
    id = map[columnId].toString();
    pwd = map[columnPwd].toString();
    name = map[columnName].toString();
    pic = map[columnPic].toString();
    done = map[columnDone] == 1;
  }
}

class TableTestProvider{
  Database? db;
  //打开数据库，并创建table_test表
  Future create(String path) async{
    db = await openDatabase(path , version: 1,
        onCreate: (Database db, int version) async{
          await db.execute(''' 
          create table $tableName(
            $columnId String primary key,
            $columnPwd String not null,
            $columnName String not null,
            $columnPic String not null,
            $columnDone integer not null ) ''');
        });
  }
  Future open(String path) async{
    db = await openDatabase(path , version: 1, );
  }
//  向表里插入
  Future<Test> insert(Test test) async {
    await db!.insert(tableName, test.toMap());
    return test;
  }
//  查询表里对应的id字段的记录
Future<Test> getTodo(String id) async{
    List<Map<String, dynamic>> maps = await db!.query(tableName,
      columns: [columnId, columnDone, columnPwd, columnName, columnPic],
      where: '$columnId = ?',
      whereArgs: [id]
    );
    if(maps.length > 0){
      return Test.fromMap(maps.first);
    }
    return Test();
}
//   删除表里对应的id字段的记录
Future<int> delete(String id) async {
    return await db!.delete(tableName, where: '$columnId = ?', whereArgs: [id]);
}
//   修改表里的某条记录
Future<int> update(Test test) async {
    return await db!.update(tableName, test.toMap(),
      where: '$columnId = ?', whereArgs: [test.id]
    );
}
//   关闭数据库
Future close() async => db!.close();
}